//
//  HJJTSQLite.m
//  YGMobile
//
//  Created by zhanglu on 2017/2/13.
//  Copyright © 2017年 Elephants Financial Service. All rights reserved.
//

#import "HJJTSQLite.h"
#include "YTXChartTools.h"

using namespace ytx;
using namespace std;

HJJTSQLite::HJJTSQLite() : BaseSQLite(){
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0];
    NSString *fileName = [NSString stringWithFormat:@"%@/HJJTData.rdb", documentsDirectory];
    path = [fileName UTF8String];
}
HJJTSQLite::~HJJTSQLite(){
    sqlite3_close(sqliteDB);
}

//bool HJJTSQLite::checkInRange(string tableName, YTXTime * outputLastTime, HJJT * gm, YTXTime time)
//{
//    if(openDB())
//    {
//        DBResult dbResult;
//        dbResult.status = false;
//        char * errmsg = 0;
//        const string queryStr = "SELECT date FROM "+ tableName+" ORDER BY date DESC LIMIT 0,1";
//        int ret = sqlite3_exec(sqliteDB, queryStr.c_str(), BaseSQLite::handelr_exec, &dbResult, &errmsg);
//        CheckResult(ret, errmsg);
//        CheckDBResult(dbResult, "checkInRange");
//        string tempTime = dbResult.getValue(0,0);
//
//        long latestValue = Tools::parseLong(tempTime);
//
//        YTXTime lastestTime = YTXTime(latestValue);
//
//        (*outputLastTime) = lastestTime;
//
////        NSLog(@"HJJTSQLite.checkInRange lastestTime:%@", [NSString stringWithUTF8String:lastestTime.toStringYYYYMMddHHmmss().c_str()] );
////        NSLog(@"HJJTSQLite.checkInRange tradeDate:%@", [NSString stringWithUTF8String: tradeDate.toStringYYYYMMddHHmmss().c_str() ]);
//
//        sqlite3_close(sqliteDB);
//        return gm->isInLatestNewK(lastestTime, time);
//    }
//    sqlite3_close(sqliteDB);
//    return false;
//}

bool HJJTSQLite::getDataFromDB(string tableName,YTXTime time, vector<HJJTItem> * gmItems, const unsigned int limit)
{
    if(openDB())
    {
        DBResult dbResult;
        dbResult.status = false;
        char * errmsg = 0;
        const string queryStr = "SELECT * FROM "+ tableName+" WHERE signalTime<"+ ConvertToString( time.getCurrentTime() ) +" ORDER BY signalTime DESC LIMIT 0,"+ConvertToString(limit);
        int ret = sqlite3_exec(sqliteDB, queryStr.c_str(), BaseSQLite::handelr_exec, &dbResult, &errmsg);
        CheckResult(ret, errmsg);
        CheckDBResult(dbResult, "getDataFromDB");
        (*gmItems) = transforDataHJJTItem(dbResult);
        sqlite3_close(sqliteDB);
        return true;
        
    }
    sqlite3_close(sqliteDB);
    return false;
}

vector<HJJTItem> HJJTSQLite::transforDataHJJTItem(DBResult & dbResult)
{
    vector<HJJTItem> result;
    
    double beginPrice, endPrice, upLine, bottom, sUpLine, upMid, downMid, sBottom;
    int trend, temper;
    HJJTPosition::HJJTPosition position;
    YTXTime tradedate, signalTime;
    unsigned int index = 0;
    unsigned int size = (unsigned int)(dbResult.row_value.size() - 1);
    //有多少列是确定的
    for (vector<vector <string> >::reverse_iterator it =  dbResult.row_value.rbegin(); it != dbResult.row_value.rend(); ++it) {
        index = size - (unsigned int)(it-dbResult.row_value.rbegin());
        signalTime = YTXTime( Tools::parseLong( dbResult.getValue(index, 0) ) );
        position = (HJJTPosition::HJJTPosition)Tools::parseInt( dbResult.getValue(index, 1) );
        beginPrice = Tools::parseDouble( dbResult.getValue(index, 2) );
        endPrice = Tools::parseDouble( dbResult.getValue(index, 3) );
        upLine = Tools::parseDouble( dbResult.getValue(index, 4) );
        bottom = Tools::parseDouble( dbResult.getValue(index, 5) );
        sUpLine = Tools::parseDouble( dbResult.getValue(index, 6) );
        upMid = Tools::parseDouble( dbResult.getValue(index, 7) );
        downMid = Tools::parseDouble( dbResult.getValue(index, 8) );
        sBottom = Tools::parseDouble( dbResult.getValue(index, 9) );
        trend = Tools::parseInt( dbResult.getValue(index, 10) );
        temper = Tools::parseInt( dbResult.getValue(index, 11) );
        
        tradedate = YTXTime( Tools::parseLong( dbResult.getValue(index, 12) ) );
        HJJTItem gs = {
            signalTime,
            position,
            beginPrice,
            endPrice,
            upLine,
            bottom,
            sUpLine,
            upMid,
            downMid,
            sBottom,
            trend,
            temper,
            tradedate
        };
        
        result.push_back(gs);
    }
    
    return result;
}


bool HJJTSQLite::insertData(string tableName, vector<HJJTItem> data)
{
    if (openDB())
    {
        char * errmsg = 0;
        sqlite3_exec(sqliteDB, "begin;", 0, 0, 0);
        
        for (vector<HJJTItem>::iterator iter = data.begin() ; iter != data.end() ; iter++ )
        {
            HJJTItem data = (*iter);
            const string sqlStrD = "DELETE FROM"+ tableName + "where signalTime = " + ConvertToString(data.signalTime.getCurrentTime());
            
            int ee = sqlite3_exec(sqliteDB, sqlStrD.c_str(), 0, 0, &errmsg);
            
            const string sqlStr = "INSERT INTO "+ tableName +" (signalTime, position, beginPrice, endPrice, upLine, bottom, sUpLine, upMid, downMid, sBottom, trend, temper, tradedate) VALUES("+ ConvertToString(data.signalTime.getCurrentTime()) + "," + ConvertToString(data.position)+","+ ConvertToString(data.beginPrice)+","+ ConvertToString(data.endPrice) + "," + ConvertToString(data.upLine)+","+ ConvertToString(data.bottom)+","+ ConvertToString(data.sUpLine) + "," + ConvertToString(data.upMid)+","+ ConvertToString(data.downMid)+","+ ConvertToString(data.sBottom) + "," + ConvertToString(data.trend)+","+ ConvertToString(data.temper)+","+ ConvertToString(data.tradedate.getCurrentTime()) +")";
            int ret = sqlite3_exec(sqliteDB, sqlStr.c_str(), 0, 0, &errmsg);
            ContinueResult(ret, errmsg);
        }
        sqlite3_exec(sqliteDB, "commit;", 0, 0, 0);
        sqlite3_close(sqliteDB);
        return true;
    }
    return false;
}

bool HJJTSQLite::createKLineDataTableIfNotExit(const string tableName)
{
    //    sqlite3_stmt *stmt = NULL;
    //    sqlite3 * sqliteDB = getDB(path, false);
    if (openDB()){
        char * errmsg = 0;
        int ret;
        const string hasTbaleSQL = "SELECT COUNT(*) FROM sqlite_master where type='table' AND name='"+tableName+"'";
        
        DBResult dbResult;
        dbResult.status = false;
        
        ret = sqlite3_exec(sqliteDB,hasTbaleSQL.c_str(), BaseSQLite::handelr_exec, &dbResult, &errmsg);
        
        CheckResult(ret, errmsg);
        
        if (Tools::parseInt(dbResult.getValue(0, 0)) > 0) {
            //            sqlite3_close(sqliteDB);
            return true;
        }
        
        const string createTableSQL =
        "CREATE TABLE "+ tableName +" (\
        signalTime INTEGER PRIMARY KEY NOT NULL UNIQUE,\
        position REAL,\
        beginPrice REAL,\
        endPrice REAL,\
        upLine REAL,\
        bottom REAL,\
        sUpLine REAL,\
        upMid REAL,\
        downMid REAL,\
        sBottom REAL,\
        trend REAL,\
        temper REAL,\
        tradedate REAL\
        )";
        
        ret = sqlite3_exec(sqliteDB,createTableSQL.c_str(), handelr_exec, &dbResult, &errmsg);
        
        CheckResult(ret, errmsg);
        
        //        sqlite3_close(sqliteDB);
        return true;
    }
    
    sqlite3_close(sqliteDB);
    return false;
}

bool HJJTSQLite::vacuumDB()
{
    if (openDB())
    {
        char * errmsg = 0;
        int ret;
        const string hasTbaleSQL = "VACUUM";
        
        DBResult dbResult;
        dbResult.status = false;
        
        ret = sqlite3_exec(sqliteDB,hasTbaleSQL.c_str(), BaseSQLite::handelr_exec, &dbResult, &errmsg);
        
        CheckResult(ret, errmsg);
        return true;
    }
    sqlite3_close(sqliteDB);
    return false;
}
